<template>
  <div>
    <el-form label-position="top" class="demo-form">
      <div class="mt-4 specification-form" v-for="(item, index) in specTypeList" :key="index">
        <!-- 规格名 -->
        <div class="pt-6 pb-6 pl-2 bg-[#F7F9FA] rounded-[6px] flex justify-between">
          <div class="w-[100%]">
            <div class="w-[100%] flex items-center">
              <!-- <el-row :gutter="24"> -->
              <el-col :span="8">
                <el-form-item label="规格名" :rules="[{ required: true, message: '规格名不能为空', trigger: 'blur' }]">
                  <!-- <el-select v-model="item.name" placeholder="规格值" @focus="getSpecList()" @change="handleNameSelect(item,index)"
                  >
                    <el-option
                      v-for="itm in specList"
                      :key="itm.id"
                      :label="itm.name"
                      :value="itm.name"
                    />
                  </el-select> -->

                   <el-autocomplete
                      v-model="item.name"
                      :fetch-suggestions="querySearchName"
                      class="inline-input w-50"
                      placeholder="规格值"
                      @focus="getSpecList()"
                      @select="handleNameSelect(item,index)"
                    />
                </el-form-item>
              </el-col>
              <img
                class="w-[52px] h-[8px] mx-2 mt-2"
                src="https://img.alicdn.com/imgextra/i1/1034622205/O1CN01P7ANKN1S9wOi58Coc_!!1034622205.png"
                alt=""
              />
              <el-col :span="8">
                <el-form-item label="规格名（外文）" :rules="[{ required: true, message: '规格名（外文）不能为空', trigger: 'blur' }]">
                  <el-input
                    v-model="item.nameForeign"
                    placeholder="规格名（外文）"
                    @input="handleInput()"
                  />
                </el-form-item>
              </el-col>
              <!-- </el-row> -->
            </div>
            <div>
              <el-checkbox v-model="item.isSpecImg" label="是否添加规格图片" />
            </div>
          </div>
          <Icon
            @click="removeSpecType(index)"
            class="absolute -translate-y-1/2 cursor-pointer top-1/2 right-2"
            icon="material-symbols:cancel"
          />
        </div>

        <!-- 规格值 -->
        <div class="mt-4">
          <el-form-item label="规格值" required>
            <div class="spec-values">
              <div class="flex flex-wrap gap-4 mb-4">
                <div
                  v-for="(itm, idx) in item.valueList"
                  :key="idx"
                  class="relative spec-value-item"
                >
                  <div class="flex items-center">
                    <!-- 判断每三个一排的第一个显示 -->
                    <div v-if="idx % 3 === 0">
                      <img
                        class="w-[25px] h-[63px]"
                        src="https://img.alicdn.com/imgextra/i3/1034622205/O1CN014RjYFW1S9wOngXZ58_!!1034622205.png"
                        alt=""
                      />
                    </div>
                    <div class="h-[100px] flex flex-col align-center justify-center">
                      <el-row :gutter="10">
                        <el-col :span="24">
                          <!-- <el-select v-model="itm.propertyValue" placeholder="规格值" @change="changePropertyValue(index,itm,idx)">
                            <el-option
                              v-for="itm in propertyValueList"
                              :key="itm.id"
                              :label="itm.name"
                              :value="itm.name"
                            />
                          </el-select> -->
                          <el-autocomplete
                            v-model="itm.propertyValue"
                            :fetch-suggestions="querySearch"
                            class="inline-input w-50"
                            placeholder="规格值"
                            @select="(item) => changePropertyValue(index, itm, idx, item.value)"
                          />
                        </el-col>
                      </el-row>
                      <el-row class="mt-2" :gutter="10">
                        <el-col :span="24">
                          <el-input
                            v-model="itm.propertyValueForeign"
                            placeholder="规格值（对应外语）"
                            style="margin-bottom: 10px"
                            @input="handleInput()"
                          />
                        </el-col>
                      </el-row>
                    </div>
                    <div
                      class="absolute cursor-pointer right--2 top--2"
                      @click="removeSpecValue(item, idx)"
                    >
                      <Icon icon="material-symbols:cancel" />
                    </div>
                  </div>
                  <div class="m-auto w-fit" v-if="item.isSpecImg">
                    <UploadImg
                      v-model="itm.picture"
                      draggable="false"
                      height="80px"
                      width="80px"
                      class="min-w-80px"
                      @change="handleInput()"
                    />
                  </div>
                </div>
                <div>
                  <el-button type="primary" link plain @click="addSpecValue(item)">
                    <el-icon><Plus /></el-icon>添加规格值
                  </el-button>
                </div>
              </div>
              <p class="text-[#999] text-[12px] mt-2 ml-6" v-if="item.isSpecImg">
                仅支持为第一组规格设置规格图片(最多60张图)，买家选择不同规格会看到对应规格图片，建议尺寸大于:800x800像素
              </p>
            </div>
          </el-form-item>
        </div>
      </div>
      <div class="specification-form mt-4 border border-solid border-[#ccc] p-4 rounded-[6px]">
        <div class="bg-[#F7F9FA] p-[10px] rounded-[6px]">
          <el-button type="default" @click="addSpec"> + 添加规格项目 </el-button>
          <p class="text-[#999] text-[12px] mt-2"
            >若有颜色、尺码、型号等多种规格供买家选择，可添加商品规格</p
          >
        </div>
      </div>
      <div class="mt-4 sku-table-container">
        <!-- <SpecificationDetails /> -->
        <el-table :data="tableData" style="width: 100%">
          <!-- 动态生成规格列 -->
          <template v-for="(spec, specIndex) in specTypeList" :key="specIndex">
            <el-table-column :label="spec.name" align="center">
              <template #default="{ row }">
                {{ getSpecValue(row, specIndex) }}
              </template>
            </el-table-column>
          </template>
          <el-table-column prop="sku" label="SKU" align="center">
            <template #default="{ row }">
              <!-- <el-input v-model="row.sku" disabled /> -->
              <span>{{ row.sku }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="saleFlag" width="120" label="是否可售" align="center">
            <template #default="{ row }">
              <el-switch v-model="row.saleFlag" :active-value="1" :inactive-value="0" />
            </template>
          </el-table-column>

          <el-table-column prop="price" label="原价">
            <template #header>
              <div class="price-header">
                <span>原价</span>
                <el-button
                  type="primary"
                  plain
                  link
                  color="#3721FF"
                  size="small"
                  @click="handleBatchEdit"
                >
                  <span>批量修改</span>
                  <Icon icon="material-symbols:edit-note" />
                </el-button>
              </div>
            </template>
            <template #default="{ row , $index }">
              <el-input class="pr-2" v-model="row.price" type="number" @input="handleInputPrice(row,$index)">
                <template #suffix>元</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="discountedPrice" label="折扣价">
            <template #default="{ row ,$index}">
              <el-input class="pl-2" type="number" v-model="row.discountedPrice" @input="handleInputPrice(row,$index)">
                <template #suffix>元</template>
              </el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <!-- 批量修改原价弹窗 -->
    <ComfirmPops
      ref="editPricePopsRef"
      :show-icon="true"
      width="500px"
      :show-dot="false"
      type="Tips"
      title="批量修改原价"
      @confirm="getEditPricePops"
    >
      <template #content>
        <el-form label-width="80px">
          <el-form-item label="原价">
            <el-input v-model="batchEdit.price" type="number" />
          </el-form-item>
          <el-form-item label="折扣价">
            <el-input v-model="batchEdit.discountedPrice" type="number" />
          </el-form-item>
        </el-form>
      </template>
    </ComfirmPops>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
const props = defineProps(['isProperty', 'specificationList', 'formData'])
import SpecificationDetails from './specificationDetails.vue'
import { ProductApi } from '@/api/product/addProduct'
import { deepCopy } from '@/utils'
import { log } from 'console'
const emit = defineEmits(['update:specTypeList', 'update:tableData'])
// const isSpecNameEn = ref(false)
interface SpecValue {
  name: string
  nameForeign: string
}
const editPricePopsRef = ref()
const dialogVisible = ref(false)
const propertyValueList = ref([])
const dialogImageUrl = ref('')
const specTypeList = ref([
  {
    name: '',
    nameForeign: '',
    isSpecImg: false,
    valueList: [
      {
        propertyValue: '',
        propertyValueForeign: '',
        picture: '', // 图片
        size: ''
      }
    ]
  }
])
const tableData = ref([
  {
    // sku: '',
    id: 0,
    name: '',
    nameForeign: '',
    remark: '',
    saleFlag: 1,
    price: 0,
    discountedPrice: 0,
    picture: '',
    propertyValue: '',
    propertyValueForeign: '',
    productId: ''
  }
])

const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? propertyValueList.value.filter(createFilter(queryString))
    : propertyValueList.value
   cb(results.map(item => ({
    value: item.name,
    nameForeign: item.nameForeign
  })));
}
const createFilter = (queryString: string) => {
  return (propertyValueList) => {
    return (
      propertyValueList.value?.toLowerCase().indexOf(queryString?.toLowerCase()) === 0
    )
  }
}
const querySearchName = (queryString: string, cb: any) => {
  const results = queryString
    ? specList.value.filter(createFilterName(queryString))
    : specList.value
   cb(results.map(item => ({
    value: item.name,
    nameForeign: item.nameForeign
  })));
}
const createFilterName = (queryString: string) => {
  return (specList) => {
    return (
      specList.value?.toLowerCase().indexOf(queryString?.toLowerCase()) === 0
    )
  }
}
// 规则列表
const specList = ref([])
const getSpecList = () => {
  ProductApi.getPropertyList({
    pageSize: 100,
    pageNum: 1,
    language: localStorage.getItem('language')
  }).then((res) => {
    specList.value = res
    console.log('specList1:', specList.value)
  })
}
// 
const handleNameSelect = (row,idx) => {
  propertyValueList.value = []
  specList.value.forEach((item,index)=>{
     if(item.name == row.name){
      propertyValueList.value = item.valueDOList
      specTypeList.value[idx].nameForeign = item.nameForeign
    }
  })
}
const changePropertyValue = (index: number, itm: any, idx: number, selectedId: number) => {
  propertyValueList.value.forEach((it)=>{
    if(itm.propertyValue == it.name){
      specTypeList.value[index].valueList[idx].propertyValueForeign = it.nameForeign
    }
  })
  handleInput()
}
// 父页面点击保存按钮的时候，调取这个页面的数据
const getTableData = () => {
  // tableData.value.map((item, index) => {
  //   item.name = Object.keys(item)
  //     .filter((key) => key.startsWith('name_'))
  //     .map((key) => item[key])
  //     .join('/')
  // })
  emit('update:tableData', tableData.value)
  return tableData.value
}
const batchEdit = reactive({
  price: '',
  discountedPrice: ''
})
// 确认批量修改原价
const getEditPricePops = () => {
  if (batchEdit.price) {
    tableData.value.forEach((item) => {
      item.price = batchEdit.price
      item.discountedPrice = batchEdit.discountedPrice
    })
    editPricePopsRef.value.hide()
  }
}
const handleBatchEdit = () => {
  editPricePopsRef.value.show()
}
const handleInput = () => {
  emit('update:specTypeList', specTypeList.value)
  specificationTable()
}
// 处理页面规格值列表
const specificationTable =  () => {
  let tableDatas =generateCombinations(specTypeList.value)
  tableData.value = JSON.parse(JSON.stringify(tableDatas)) 
}
const addSpecValue = (item) => {
  item.valueList.push({
    propertyValue: '',
    propertyValueForeign: '',
    picture: ''
  })
  specificationTable()
  emit('update:specTypeList', specTypeList.value)
  // tableData.value.push({
  //   // sku: '',
  //   name: '',
  //   nameForeign: '',
  //   remark: '',
  //   saleFlag: 0,
  //   price: 0,
  //   discountedPrice: 0,
  //   picture: '',
  //   propertyValue: '',
  //   propertyValueForeign: '',
  //   productId: '',
  //   id: 0
  // })
  // emit('update:tableData', tableData.value)
  propertyValueList.value = []
  specList.value.forEach((itm,index)=>{
    if(item.name == itm.name){
      propertyValueList.value = itm.valueDOList
    }
  })
}
const addSpec = () => {
  specTypeList.value.push({
    name: '',
    nameForeign: '',
    isSpecImg: false,
    valueList: [
      {
        propertyValue: '',
        propertyValueForeign: '',
        picture: ''
      }
    ]
  })
  specificationTable()
  emit('update:specTypeList', specTypeList.value)
}
const removeSpecValue = (item, idx) => {
  if (item.valueList.length == 1) {
    ElMessage.warning('至少保留一个规格值')
    return
  }
  item.valueList.splice(idx, 1)
  specificationTable()
}
const removeSpecType = (index) => {
  if (specTypeList.value.length == 1) {
    ElMessage.warning('至少保留一个规格项')
    return
  }
  specTypeList.value.splice(index, 1)
  emit('update:specTypeList', specTypeList.value)
  specificationTable()
}

// 笛卡尔积计算
function cartesianProduct(arrays) {
  return arrays.reduce((acc, currentArray) => {
    const result = []
    acc.forEach((prevItem) => {
      currentArray.forEach((currentItem) => {
        result.push([...prevItem, currentItem])
      })
    })
    return result.length ? result : currentArray.map((item) => [item])
  }, [])
}

// 生成组合数据
function generateCombinations(specs) {

  const valueLists = specs.map((spec) => spec.valueList)
  const combinations = cartesianProduct(valueLists)

  let orTableList = deepCopy(tableData.value)

  return combinations.map((items,indexs) => {
    let row: SkuItem = {
      // sku: '',
      name: '',
      nameForeign: '',
      remark: '',
      saleFlag: 1,
      price: 0,
      discountedPrice: 0,
      picture: '',
      propertyValue: '', //规格值
      propertyValueForeign: '' //规格值外文
    }
    // 收集所有规格信息
    const specNames = []
    const specNamesForeign = []
    const specValues = []
    const specValuesForeign = []
    const pictures = []

    items.forEach((item, index) => {
      const spec = specs[index]

      // 设置单个规格的属性
      row[`name_${index}`] = item.propertyValue // 中文规格值
      row[`name_foreign_${index}`] = spec.nameForeign // 规格名外文
      row[`value_foreign_${index}`] = item.propertyValueForeign // 规格值外文

      // 收集用于组合
      specNames.push(spec.name)
      specNamesForeign.push(spec.nameForeign)
      specValues.push(item.propertyValue)
      specValuesForeign.push(item.propertyValueForeign)
      pictures.push(item.picture) // 收集图片
    })
    // 设置组合后的值
    row.name = specNames.join('§')
    row.nameForeign = specNamesForeign.join('§')
    row.propertyValue = specValues.join('§')
    row.propertyValueForeign = specValuesForeign.join('§')
    row.picture = pictures.join(',') // 用逗号分隔所有图片
    
    // row.sku = orTableList[indexs]?.sku // 生成SKU
    row.saleFlag = orTableList[indexs]?.saleFlag ?? 1
    row.price =  orTableList[indexs]?.price
    row.discountedPrice =  orTableList[indexs]?.discountedPrice

    return row
  })
}
const handleInputPrice = (row,index) => {
  tableData.value[index].price = row.price
  tableData.value[index].discountedPrice = row.discountedPrice
  tableData.value[index].saleFlag = row.saleFlag ?? 1
  emit('update:tableData', tableData.value)
}
const getSpecValue = (row, specIndex) => {
  return row[`name_${specIndex}`] || ''
}
// 从表格数据还原规格类型结构
const restoreSpecTypeList = (tableData) => {
  if (!tableData || tableData.length === 0) return []
  const firstRow = tableData[0]
  console.log(firstRow);
  
  // 1. 解析规格结构
  const nameParts = firstRow.name?.split('§')
  const nameForeignParts = firstRow.nameForeign?.split('§')
  const propertyValueParts = firstRow.propertyValue?.split('§')
  const propertyValueForeignParts = firstRow.propertyValueForeign?.split('§')
  const pictureParts = firstRow.picture?.split(',') || []

  const specCount = nameParts?.length

  // 2. 构建规格类型列表
  const newSpecTypeList = []

  for (let i = 0; i < specCount; i++) {
    // 收集该规格的所有可能值
    const valuesMap = new Map()

    tableData.forEach((row) => {
      // 从组合字段中拆分出各部分值
      const currentPropertyValues = row.propertyValue?.split('§')
      const currentPropertyValueForeigns = row?.propertyValueForeign?row?.propertyValueForeign?.split('§'):[]
      const currentPictures = row.picture?.split(',') || []

      const propertyValue = currentPropertyValues[i]
      const propertyValueForeign = currentPropertyValueForeigns[i]
      const picture = currentPictures[i] || ''

      const key = `${propertyValue}-${propertyValueForeign}`
      if (!valuesMap.has(key)) {
        valuesMap.set(key, {
          propertyValue,
          propertyValueForeign,
          picture: picture // 使用对应的图片
        })
      }
    })
    
    newSpecTypeList.push({
      name: nameParts?nameParts[i]:'',
      nameForeign: nameForeignParts?nameForeignParts[i]:'',
      // isSpecImg: i === 0, // 第一组规格可以设置图片
      valueList: Array.from(valuesMap.values())
    })
  }

  return newSpecTypeList
}
watch(
  () => specTypeList.value,
  (newVal) => {
    console.log('specTypeList', newVal)
     let tableDatas =generateCombinations(newVal)
    tableData.value = JSON.parse(JSON.stringify(tableDatas))  
    console.log('tableData.value======898', tableData.value)
    emit('update:specTypeList', newVal)
  },
  {
    deep: true
  }
)

watch(
  () => props.specificationList,
  (newVal) => {
    if (newVal) {
      console.log(props.specificationList,'specificationList');
      
      specTypeList.value = restoreSpecTypeList(newVal)
      // 如果specTypeList.value.valueList里面的picture有数据，就把外层的isSpecImg改为true;
      specTypeList.value.map((item) => {
        if (item.valueList.some((itm) => itm.picture != '')) {
          item.isSpecImg = true
        }
      })
      tableData.value = newVal.map((row) => {
        // 确保每一行都有所有必要的动态字段
        const nameParts = row.name?.split('§')
        const nameForeignParts = row.nameForeign?.split('§')
        const propertyValueParts = row.propertyValue?.split('§')
        const propertyValueForeignParts = row.propertyValueForeign?.split('§')
        const newRow = { ...row }

        // 添加动态字段
        if (!nameParts || !nameForeignParts || !propertyValueParts || !propertyValueForeignParts) {
          return newRow
        }
        nameParts?.forEach((part, index) => {
          newRow[`name_${index}`] = propertyValueParts[index]
          newRow[`name_foreign_${index}`] = nameForeignParts[index]
          newRow[`value_foreign_${index}`] = propertyValueForeignParts[index]
        })
        return newRow
      })
    }
  },
  { immediate: true, deep: true }
)
const updateTableData = () => {
  emit('update:specTypeList', specTypeList.value)
  specificationTable()
  console.log(specTypeList.value, 'specTypeList.value6678');
  console.log(tableData.value, 'tableData.value');
  
  // const userInputs = tableData.value.map((item) => ({
  //   price: item.price,
  //   discountedPrice: item.discountedPrice,
  //   saleFlag: item.saleFlag,
  //   ...item
  // }))
  // tableData.value.forEach((newItem, index) => {
  //   if (userInputs[index]) {
  //     Object.assign(newItem, userInputs[index])
  //   }
  // })
  return tableData.value
}
onMounted(() => {
  console.log('props.isProperty', props.isProperty)
  getSpecList()
})
defineExpose({
  getTableData,
  updateTableData
})
</script>

<style scoped lang="scss">
.specification-form {
  max-width: 800px;
  padding: 10px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.spec-values {
  width: 100%;
}

.spec-value-item {
  // display: flex;
  // align-items: center;
  // gap: 10px;
  // margin-bottom: 15px;
  // position: relative;

  .remove-btn {
    position: absolute;
    right: -40px;
  }
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  line-height: 1.5;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}

.sku-table-container {
  // max-width: 800px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.price-header {
  display: flex;
  align-items: center;
}

.add-row {
  margin-top: 15px;
  text-align: center;
}

:deep(.el-table .cell) {
  padding: 8px 0;
}

:deep(.el-input__suffix) {
  display: flex;
  align-items: center;
  margin-right: 5px;
  color: #999;
}
</style>
